package classes
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.getQualifiedClassName;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
		
	[Bindable]
	public class ReturnedImage extends EventDispatcher
	{
		public var title:String;
		public var width:Number;
		public var height:Number;
		public var url:String;
		public var thumbURL:String;
		public var globalRank:Number;
		public var colorScore:Number;
		public var textureScore:Number;
		public var similarity:Number;
		public var clippedSimilarity:Number;
		public var clippedScore:Number;
		public var isRemote:Boolean;
		public var originalURL:String;
		public var imageURI:String;
		[Bindable ("tagsUpdated")]
		public var tags:ArrayCollection;
		
		public function ReturnedImage(title:String, width:Number, height:Number, url:String, thumbURL:String, globalRank:Number=0, colorScore:Number=0, textureScore:Number=0, similarity:Number=0, isRemote:Boolean=false, originalURL:String="", imageURI:String=""){
			super();
			this.title = title;
			this.width = width;
			this.height = height;
			this.url = url;
			this.thumbURL = thumbURL;
			this.globalRank = globalRank;
			this.colorScore = colorScore;
			this.textureScore = textureScore;
			this.similarity = similarity;
			this.isRemote = isRemote;
			this.originalURL = originalURL;
			this.imageURI = imageURI;
			tags = new ArrayCollection();
		}
		
		public function refreshTags():void{
			dispatchEvent (new Event("refreshingTags"));
			var servletReq:HTTPService = new HTTPService();
			servletReq.method = "POST";
			servletReq.url = Settings.getInstance().getImageTagsServletURL;
			servletReq.addEventListener(ResultEvent.RESULT, getImageTagsResultHandler);
			servletReq.send({imageURI: this.imageURI});
		}
		
		public function getImageTagsResultHandler(event:ResultEvent):void{
			tags = new ArrayCollection();
			var resItem:Object = event.result;
			if(event.result.toString() == "FAIL"){
				dispatchEvent(new Event("tagRefreshError"));
			}else{
				if(event.result.tags!=null && event.result.tags.hasOwnProperty("tag")){
								if(getQualifiedClassName(event.result.tags.tag) == "String"){
									tags.addItem(event.result.tags.tag);
								}else{
									for each(var tag:String in event.result.tags.tag){
										tags.addItem(tag);
									}
								}
							}
				dispatchEvent(new Event("tagsUpdated"));
			}
		}
	}
}